package com.xy.shop.wechat.handler.gzh1;

import com.xy.shop.web.entity.WxUser;
import com.xy.shop.web.service.WxUserService;
import com.xy.shop.wechat.builder.NewsBuilder;
import com.xy.shop.wechat.builder.TextBuilder;
import com.xy.shop.wechat.config.WxConfig;
import com.xy.shop.wechat.config.WxGzh1Config;
import com.xy.shop.wechat.dto.WechatSubscribe;
import com.xy.shop.wechat.handler.SubscribeHandler;
import com.xy.shop.wechat.service.BaseWxService;
import com.xy.shop.wechat.service.WechatSubscribeService;
import com.xy.shop.wechat.service.impl.WechatSubscribeServiceImpl;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Component
public class Gzh1SubscribeHandler extends SubscribeHandler
{
	
	/*@Value("${qshdGameType}")
	private String qshdGameType;*/
	
	@Autowired
	private WxGzh1Config wxGzh1Config;
	
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	
	@Resource
	private WechatSubscribeService subscribeService;

	@Resource
	private WxUserService wxUserService;
	
	@Override
	protected WxConfig getWxConfig()
	{
		return this.wxGzh1Config;
	}
	
	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
			Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException
	{
		
		this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
		
		BaseWxService weixinService = (BaseWxService) wxMpService;
		
		// 获取微信用户基本信息
		WxMpUser userWxInfo = weixinService.getUserService()
				.userInfo(wxMessage.getFromUser(), null);
		String weChatText = "歡迎關注。0.0000";
		 WechatSubscribe ws = new WechatSubscribe();

		if (userWxInfo != null)
		{
			ws.setOpenid(userWxInfo.getOpenId());
			ws.setNickname(userWxInfo.getNickname());
			String sex="0";
			if("男".equals(userWxInfo.getSex())){
				sex="1";
			}else if("女".equals(userWxInfo.getSex())){
				sex="2";
			}
			ws.setSex(sex);
			ws.setCity(userWxInfo.getCity());
			ws.setCountry(userWxInfo.getCountry());
			ws.setProvince(userWxInfo.getProvince());
			ws.setLanguage(userWxInfo.getLanguage());
			ws.setHeadImgUrl(userWxInfo.getHeadImgUrl());
			ws.setSubscribe(userWxInfo.getSubscribe() == true ? 1 : 0);
			ws.setSubscribeTime(
					Integer.parseInt(userWxInfo.getSubscribeTime() + ""));
			ws.setUnionid(userWxInfo.getUnionId());
			ws.setRemark(userWxInfo.getRemark());
			ws.setGroupid(userWxInfo.getGroupId());

			weChatText = "欢迎加入！";// 统一回复文本简单，不超过50字
			subscribeService.insertSelective(ws);

			if (StringUtils.isNotBlank(ws.getOpenid())) {
				WxUser wxUser =wxUserService.selectByOpendId(ws.getOpenid());
				if(Objects.isNull(wxUser)){
					wxUser=new WxUser();
					wxUser.setIcon(userWxInfo.getHeadImgUrl());
					wxUser.setSex(Integer.valueOf(ws.getSex()));
					wxUser.setOpenId(userWxInfo.getOpenId());
					wxUser.setName(userWxInfo.getNickname());
					int count=wxUserService.updateByPrimaryKeySelective(wxUser);
					logger.info("微信关注用户信息添加 wx_user:"+wxUser.toString());
					logger.debug("微信关注用户信息添加 wx_user:"+wxUser.toString());
				}
			}
			return new NewsBuilder().build(weChatText, wxMessage,weixinService);
			
			
		}
		
		WxMpXmlOutMessage responseResult = null;
		try
		{
			responseResult = handleSpecial(wxMessage);
		} catch (Exception e)
		{
			this.logger.error(e.getMessage(), e);
		}
		
		if (responseResult != null)
		{
			return responseResult;
		}
		
		try
		{
			return new TextBuilder().build(weChatText, wxMessage,
					weixinService);
		} catch (Exception e)
		{
			this.logger.error(e.getMessage(), e);
		}
		
		return null;
	}
	
	@Override
	protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
	{
		return null;
	}
	
}
